package io.hellsinger.vortex.service.storage.transaction

import io.hellsinger.filesystem.linux.error.ErrnoException
import io.hellsinger.filesystem.linux.operation.rename
import io.hellsinger.vortex.service.model.Dest
import io.hellsinger.vortex.service.model.Source

class MoveTransaction(
    private val sources: List<Source>,
    private val dest: Dest,
) : StorageTransaction() {
    override suspend fun perform(): Result {
        for (i in 0 until sources.lastIndex) {
            val source = sources[i]
            val sourceName = source.path.getNameAt()
            val destEntry =
                if (sourceName == dest.path.getNameAt()) {
                    source.path
                } else {
                    dest.path.resolve(sourceName)
                }

            try {
                // TODO: Add implementation if source and dest are in different file systems
                // Fast way
                source.path.rename(destEntry)
            } catch (exception: ErrnoException) {
            }
        }

        closeNotificationAfter(1000)

        return Result.Success
    }
}
